package fr.perso.ppo.springintegration.error;

import java.util.Collection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.integration.Message;
import org.springframework.integration.MessageHandlingException;
import org.springframework.integration.history.MessageHistory;

public class ErrorChannelTransformer {

	private static Logger log = LoggerFactory.getLogger(ErrorChannelTransformer.class);

	public Object transform(Message<?> msg) throws Exception {
		log.warn("==================get into error channel /////////////////////");
		ErrorChannelMessage errorMsg = new ErrorChannelMessage();
		
		//TODO responsibility chain

		if (msg.getPayload() instanceof MessageHandlingException) {
			MessageHandlingException payload = (MessageHandlingException) msg.getPayload();
			log.warn(payload.getMessage(), payload.getCause());
			log.warn("--------------------------------- {}", payload.getFailedMessage().getPayload());
			// Message<?> originalMsg =
			// (Message<?>)payload.getFailedMessage().getPayload();
			String originalMsg;
			Object originalPayload = payload.getFailedMessage().getPayload();
			if (originalPayload instanceof Map || originalPayload instanceof Collection)
				originalMsg = payload.getFailedMessage().getPayload().toString();
			else
				originalMsg = (String) payload.getFailedMessage().getPayload();
			log.warn("************************this is the original message {}*************************", originalMsg.toString());

			// ErrorChannelMessage errorMsg = new ErrorChannelMessage();
			errorMsg.setMessage(payload.getMessage());
			errorMsg.setFailedMessage(payload.getFailedMessage().getPayload());
			errorMsg.setMessageHistory(msg.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class));
			errorMsg.setFailedMessageHistory(payload.getFailedMessage().getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class));
		} else {
			if (msg.getPayload() instanceof TaskRejectedException) {
				TaskRejectedException payload = (TaskRejectedException) msg.getPayload();
				errorMsg.setMessage(payload.getMessage());
				errorMsg.setMessageHistory(msg.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class));
			}
		}
		return errorMsg;
	}

}
